import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controllers/home_controller.dart';
import '../../../services/theme_service.dart';
import '../../../services/locale_service.dart';
import '../../../translations/app_translations.dart';
import '../../../routes/app_routes.dart';
import '../../../models/alert_log_model.dart';
import '../../../utils/themes/app_theme.dart';
import '../../../utils/themes/app_theme_extension.dart';

class HomeView extends GetView<HomeController> {
  const HomeView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // 获取主题扩展
    final themeExt = AppTheme.extensionOf(context);
    final themeService = Get.find<ThemeService>();
    
    // 定义卡片形状 - 更现代的圆角
    final cardShape = RoundedRectangleBorder(
      borderRadius: BorderRadius.circular(themeExt.cardRadius * 1.2),
    );
    
    return Scaffold(
      appBar: AppBar(
        title: Obx(() => controller.userService.currentUserRx.value != null
          ? GestureDetector(
              onTap: () => Get.toNamed(Routes.profile),
              child: Row(
                children: [
                  _buildUserAvatar(context),
                  const SizedBox(width: 8),
                  Text(
                    '${LocaleKeys.hello.tr}${controller.userService.nickName}',
                    style: const TextStyle(
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ],
              ),
            )
          : const Text(LocaleKeys.homeTitle)
        ),
        centerTitle: false,
        actions: [
          // 主题切换按钮
          IconButton(
            tooltip: LocaleKeys.changeTheme.tr,
            onPressed: () => themeService.switchTheme(),
            icon: Icon(Get.isDarkMode ? Icons.light_mode : Icons.dark_mode),
          ),
          // 语言菜单
          PopupMenuButton<String>(
            tooltip: LocaleKeys.changeLanguage.tr,
            onSelected: (value) {
              if (value == 'zh_CN') {
                LocaleService().switchToChinese();
              } else if (value == 'en_US') {
                LocaleService().switchToEnglish();
              } else if (value == 'ko_KR') {
                LocaleService().switchToKorean();
              } else if (value == 'ar_SA') {
                LocaleService().switchToArabic();
              }
            },
            itemBuilder: (context) => [
              PopupMenuItem(
                value: 'zh_CN',
                child: Text(LocaleKeys.chinese.tr),
              ),
              PopupMenuItem(
                value: 'en_US',
                child: Text(LocaleKeys.english.tr),
              ),
              PopupMenuItem(
                value: 'ko_KR',
                child: Text(LocaleKeys.korean.tr),
              ),
              PopupMenuItem(
                value: 'ar_SA',
                child: Text(LocaleKeys.arabic.tr),
              ),
            ],
            icon: const Icon(Icons.language),
          ),
          // 登出按钮
          IconButton(
            tooltip: LocaleKeys.logout.tr,
            onPressed: () => controller.logout(),
            icon: const Icon(Icons.logout),
          ),
        ],
        elevation: 0,
      ),
      body: RefreshIndicator(
        onRefresh: () async {
          // 使用静默刷新方法，仅刷新数据而不刷新UI
          await controller.silentRefreshData();
        },
        color: Theme.of(context).primaryColor,
        backgroundColor: themeExt.cardBackground,
        displacement: 40,
        strokeWidth: 3.0,
        // 使用NotificationListener实现下拉状态监听
        child: NotificationListener<ScrollNotification>(
          onNotification: (ScrollNotification notification) {
            // 可以在这里处理滚动通知
            return false;
        },
        child: SingleChildScrollView(
          physics: const AlwaysScrollableScrollPhysics(),
          child: Padding(
            padding: const EdgeInsets.fromLTRB(16, 8, 16, 24),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // 产品统计信息
                  Obx(() => controller.isLoading.value && !controller.isRefreshing.value
                  ? const Padding(
                      padding: EdgeInsets.all(20.0),
                      child: CircularProgressIndicator(),
                    )
                  : Card(
                      elevation: 2,
                      shadowColor: themeExt.cardShadow.withOpacity(0.3),
                      shape: cardShape,
                      color: themeExt.cardBackground,
                      margin: const EdgeInsets.only(bottom: 16, top: 8),
                      child: Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            // 产品统计信息标题行
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Expanded(
                                  child: SingleChildScrollView(
                                    scrollDirection: Axis.horizontal,
                                    child: Row(
                                      mainAxisSize: MainAxisSize.min,
                                      children: [
                                        Container(
                                          padding: const EdgeInsets.all(8),
                                          decoration: BoxDecoration(
                                            color: Theme.of(context).primaryColor.withOpacity(0.1),
                                            borderRadius: BorderRadius.circular(8),
                                          ),
                                          child: Icon(
                                            Icons.devices_other,
                                            color: Theme.of(context).primaryColor,
                                          ),
                                        ),
                                        const SizedBox(width: 12),
                                        Text(
                                          LocaleKeys.productStats.tr,
                                          style: const TextStyle(
                                            fontSize: 18, 
                                            fontWeight: FontWeight.bold
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                                TextButton(
                                  onPressed: () => Get.toNamed(Routes.product),
                                  style: TextButton.styleFrom(
                                    padding: const EdgeInsets.symmetric(horizontal: 12),
                                  ),
                                  child: Row(
                                    mainAxisSize: MainAxisSize.min,
                                    children: [
                                      Text(
                                        LocaleKeys.viewAll.tr,
                                        style: TextStyle(
                                          color: Theme.of(context).primaryColor,
                                          fontWeight: FontWeight.w500,
                                        ),
                                      ),
                                      const SizedBox(width: 2),
                                      Icon(Icons.arrow_forward_ios, size: 14, color: Theme.of(context).primaryColor),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                            const SizedBox(height: 20),
                            // 使用和设备统计相同的网格布局
                            GridView.count(
                              crossAxisCount: 2,
                              crossAxisSpacing: 12,
                              mainAxisSpacing: 12,
                              shrinkWrap: true,
                              childAspectRatio: 2.2,
                              physics: const NeverScrollableScrollPhysics(),
                              children: [
                                // 产品总数
                                _buildStatisticCard(
                                  context: context,
                                  icon: Icons.devices, 
                                  label: LocaleKeys.totalProducts.tr,
                                  value: controller.productCount.value.toString(),
                                  color: Theme.of(context).primaryColor,
                                  onTap: () => Get.toNamed(Routes.product),
                                ),
                                // 物模型产品数
                                _buildStatisticCard(
                                  context: context,
                                  icon: Icons.device_unknown, 
                                  label: LocaleKeys.totalModels.tr,
                                  value: controller.productsWithoutModelCount.value.toString(),
                                  color: Colors.orange,
                                  onTap: () => Get.toNamed(Routes.productModel, arguments: {'hasModel': true}),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    )
                ),
                
                // 设备统计信息
                  Obx(() => controller.isLoading.value && !controller.isRefreshing.value
                  ? const SizedBox.shrink()
                  : Card(
                      elevation: 2,
                      shadowColor: themeExt.cardShadow.withOpacity(0.3),
                      shape: cardShape,
                      color: themeExt.cardBackground,
                      margin: const EdgeInsets.only(bottom: 16),
                      child: Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            // 设备统计信息标题行
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Expanded(
                                  child: SingleChildScrollView(
                                    scrollDirection: Axis.horizontal,
                                    child: Row(
                                      mainAxisSize: MainAxisSize.min,
                                      children: [
                                        Container(
                                          padding: const EdgeInsets.all(8),
                                          decoration: BoxDecoration(
                                            color: Colors.purple.withOpacity(0.1),
                                            borderRadius: BorderRadius.circular(8),
                                          ),
                                          child: const Icon(
                                            Icons.important_devices,
                                            color: Colors.purple,
                                          ),
                                        ),
                                        const SizedBox(width: 12),
                                        Text(
                                          LocaleKeys.deviceStats.tr,
                                          style: const TextStyle(
                                            fontSize: 18, 
                                            fontWeight: FontWeight.bold
                                          ),
                                        ),
                                        const SizedBox(width: 8),
                                        Container(
                                          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                                          decoration: BoxDecoration(
                                            color: Colors.purple.shade100.withOpacity(0.6),
                                            borderRadius: BorderRadius.circular(themeExt.tagRadius),
                                          ),
                                          child: Text(
                                            "${LocaleKeys.totalCount.tr}: ${controller.deviceTotalCount.value}",
                                            style: const TextStyle(
                                              fontSize: 14,
                                              color: Colors.purple,
                                              fontWeight: FontWeight.bold,
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                                TextButton(
                                  onPressed: () => Get.toNamed(Routes.device),
                                  style: TextButton.styleFrom(
                                    padding: const EdgeInsets.symmetric(horizontal: 12),
                                  ),
                                  child: Row(
                                    mainAxisSize: MainAxisSize.min,
                                    children: [
                                      Text(
                                        LocaleKeys.viewAll.tr,
                                        style: TextStyle(
                                          color: Theme.of(context).primaryColor,
                                          fontWeight: FontWeight.w500,
                                        ),
                                      ),
                                      const SizedBox(width: 2),
                                      Icon(Icons.arrow_forward_ios, size: 14, color: Theme.of(context).primaryColor),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                            const SizedBox(height: 20),
                            // 使用网格布局 - 设计接近截图中的样式
                            GridView.count(
                              crossAxisCount: 2,
                              crossAxisSpacing: 12,
                              mainAxisSpacing: 12,
                              shrinkWrap: true,
                              childAspectRatio: 2.2,
                              physics: const NeverScrollableScrollPhysics(),
                              children: [
                                // 在线设备 - 状态码 1
                                _buildStatisticCard(
                                  context: context,
                                  icon: Icons.cloud_done, 
                                  label: LocaleKeys.onlineDevices.tr,
                                  value: controller.deviceOnlineCount.value.toString(),
                                  color: themeExt.successText,
                                  onTap: () => Get.toNamed(Routes.device, arguments: {'status': 1}),
                                ),
                                // 离线设备 - 状态码 2
                                _buildStatisticCard(
                                  context: context,
                                  icon: Icons.cloud_off, 
                                  label: LocaleKeys.offlineDevices.tr,
                                  value: controller.deviceOfflineCount.value.toString(),
                                  color: themeExt.errorText,
                                  onTap: () => Get.toNamed(Routes.device, arguments: {'status': 2}),
                                ),
                                // 禁用设备 - 状态码 3
                                _buildStatisticCard(
                                  context: context,
                                  icon: Icons.block,
                                  label: LocaleKeys.disabledDevices.tr,
                                  value: controller.deviceDisabledCount.value.toString(),
                                  color: themeExt.errorText,
                                  onTap: () => Get.toNamed(Routes.device, arguments: {'status': 3}),
                                ),
                                // 未激活设备 - 状态码 0
                                _buildStatisticCard(
                                  context: context,
                                  icon: Icons.pending_actions, 
                                  label: LocaleKeys.inactiveDevices.tr,
                                  value: controller.deviceInactiveCount.value.toString(),
                                  color: themeExt.disabledText,
                                  onTap: () => Get.toNamed(Routes.device, arguments: {'status': 0}),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    )
                ),
                
                // 告警状态统计
                Obx(() => controller.isLoading.value && !controller.isRefreshing.value
                  ? const SizedBox.shrink()
                  : Card(
                    elevation: 2,
                    shadowColor: themeExt.cardShadow.withOpacity(0.3),
                    shape: cardShape,
                    color: themeExt.cardBackground,
                    margin: const EdgeInsets.only(bottom: 16),
                    child: Padding(
                      padding: const EdgeInsets.all(16.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          // 告警统计信息标题行
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Expanded(
                                child: SingleChildScrollView(
                                  scrollDirection: Axis.horizontal,
                                  child: Row(
                                    mainAxisSize: MainAxisSize.min,
                                    children: [
                                      Container(
                                        padding: const EdgeInsets.all(8),
                                        decoration: BoxDecoration(
                                          color: themeExt.errorText.withOpacity(0.1),
                                          borderRadius: BorderRadius.circular(8),
                                        ),
                                        child: Icon(
                                          Icons.warning_amber_rounded,
                                          color: themeExt.errorText,
                                        ),
                                      ),
                                      const SizedBox(width: 12),
                                      Text(
                                        LocaleKeys.alertStats.tr,
                                        style: const TextStyle(
                                          fontSize: 18, 
                                          fontWeight: FontWeight.bold
                                        ),
                                      ),
                                      const SizedBox(width: 8),
                                      // 添加告警总数显示
                                      Container(
                                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                                        decoration: BoxDecoration(
                                          color: themeExt.infoBg,
                                          borderRadius: BorderRadius.circular(themeExt.tagRadius),
                                        ),
                                        child: Obx(() => Text(
                                          "${LocaleKeys.totalCount.tr}: ${controller.alertLogsTotal.value}",
                                          style: TextStyle(
                                            fontSize: 14,
                                            color: themeExt.infoText,
                                            fontWeight: FontWeight.bold,
                                          ),
                                        )),
                                      ),
                                      const SizedBox(width: 8),
                                      Obx(() => controller.unconfirmedAlertCount.value > 0
                                        ? Container(
                                          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                                          decoration: BoxDecoration(
                                            color: themeExt.errorBg,
                                            borderRadius: BorderRadius.circular(themeExt.tagRadius),
                                          ),
                                          child: Row(
                                            mainAxisSize: MainAxisSize.min,
                                            children: [
                                              Icon(
                                                Icons.notifications_active, 
                                                color: themeExt.errorText, 
                                                size: 14,
                                              ),
                                              const SizedBox(width: 4),
                                              Text(
                                                "${controller.unconfirmedAlertCount.value}${LocaleKeys.unconfirmedCount.tr}",
                                                style: TextStyle(
                                                  fontSize: 14,
                                                  color: themeExt.errorText,
                                                  fontWeight: FontWeight.bold,
                                                ),
                                              ),
                                            ],
                                          ),
                                        )
                                        : const SizedBox.shrink()
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                              TextButton(
                                onPressed: () {
                                  // 跳转到告警日志列表页面
                                  Get.toNamed(Routes.alertLogs);
                                },
                                style: TextButton.styleFrom(
                                  padding: const EdgeInsets.symmetric(horizontal: 12),
                                ),
                                child: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    Text(
                                      LocaleKeys.viewAll.tr,
                                      style: TextStyle(
                                        color: Theme.of(context).primaryColor,
                                        fontWeight: FontWeight.w500,
                                      ),
                                    ),
                                    const SizedBox(width: 2),
                                    Icon(Icons.arrow_forward_ios, size: 14, color: Theme.of(context).primaryColor),
                                  ],
                                ),
                              ),
                            ],
                          ),
                          const SizedBox(height: 20),
                          
                          // 告警状态统计数据内容
                          controller.isLoadingAlerts.value && !controller.isRefreshing.value
                          ? const Center(
                              child: Padding(
                                padding: EdgeInsets.all(16.0),
                                child: CircularProgressIndicator(),
                              ),
                            )
                          : controller.alertLogsTotal.value == 0
                          ? Container(
                              padding: const EdgeInsets.symmetric(vertical: 20),
                              alignment: Alignment.center,
                              child: Text(
                                LocaleKeys.noAlertInfo.tr,
                                style: TextStyle(
                                  color: themeExt.textSecondary,
                                  fontSize: 16,
                                ),
                              ),
                            )
                          : LayoutBuilder(
                              builder: (context, constraints) {
                                // 计算每个卡片的宽度 (总宽度减去间距) / 3
                                final cardWidth = (constraints.maxWidth - 24) / 3;
                                // 设置固定的高度，确保不会溢出
                                const cardHeight = 112.0;
                                
                                return Wrap(
                                  spacing: 12,
                                  runSpacing: 12,
                                  children: [
                                    // 产生告警
                                    SizedBox(
                                      width: cardWidth,
                                      height: cardHeight,
                                      child: _buildAlertStatusCard(
                                        context: context,
                                        label: LocaleKeys.alertStatusGenerated.tr,
                                        value: controller.alertGeneratedCount.value.toString(),
                                        color: themeExt.errorText,
                                        icon: Icons.warning_amber_rounded,
                                        onTap: () => {
                                          // 如果没有未处理的告警，则显示提示
                                          if (controller.alertGeneratedCount.value <= 0)
                                            Get.snackbar(
                                              LocaleKeys.tip.tr, 
                                              LocaleKeys.noUnprocessedAlerts.tr,
                                              snackPosition: SnackPosition.BOTTOM,
                                              duration: const Duration(seconds: 2),
                                            )
                                          else
                                            Get.toNamed(Routes.alertLogs, arguments: {'status': 0})
                                        },
                                      ),
                                    ),
                                    // 已恢复告警
                                    SizedBox(
                                      width: cardWidth,
                                      height: cardHeight,
                                      child: _buildAlertStatusCard(
                                        context: context,
                                        label: LocaleKeys.alertStatusRecovered.tr,
                                        value: controller.alertRecoveredCount.value.toString(),
                                        color: themeExt.successText,
                                        icon: Icons.check_circle_outline,
                                        onTap: () => {
                                          // 如果没有已恢复的告警，则显示提示
                                          if (controller.alertRecoveredCount.value <= 0)
                                            Get.snackbar(
                                              LocaleKeys.tip.tr, 
                                              LocaleKeys.noRecoveredAlerts.tr,
                                              snackPosition: SnackPosition.BOTTOM,
                                              duration: const Duration(seconds: 2),
                                            )
                                          else
                                            Get.toNamed(Routes.alertLogs, arguments: {'status': 1})
                                        },
                                      ),
                                    ),
                                    // 已确认告警
                                    SizedBox(
                                      width: cardWidth,
                                      height: cardHeight,
                                      child: _buildAlertStatusCard(
                                        context: context,
                                        label: LocaleKeys.alertStatusConfirmed.tr,
                                        value: controller.alertConfirmedCount.value.toString(),
                                        color: themeExt.disabledText,
                                        icon: Icons.done_all,
                                        onTap: () => {
                                          // 如果没有已确认的告警，则显示提示
                                          if (controller.alertConfirmedCount.value <= 0)
                                            Get.snackbar(
                                              LocaleKeys.tip.tr, 
                                              LocaleKeys.noConfirmedAlerts.tr,
                                              snackPosition: SnackPosition.BOTTOM,
                                              duration: const Duration(seconds: 2),
                                            )
                                          else
                                            Get.toNamed(Routes.alertLogs, arguments: {'status': 2})
                                        },
                                      ),
                                    ),
                                  ],
                                );
                              },
                            ),
                        ],
                      ),
                    ),
                  )
                ),
                  
                  // 额外的空间，确保可以下拉刷新
                  const SizedBox(height: 60),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
  
  // 更简洁统一的卡片样式
  Widget _buildStatisticCard({
    required BuildContext context,
    required IconData icon,
    required String label,
    required String value,
    required Color color,
    Function()? onTap,
  }) {
    final themeExt = AppTheme.extensionOf(context);
    
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(themeExt.cardRadius),
        child: Container(
          decoration: BoxDecoration(
            color: themeExt.cardBackground,
            borderRadius: BorderRadius.circular(themeExt.cardRadius),
            boxShadow: [
              BoxShadow(
                color: themeExt.cardShadow.withOpacity(0.1),
                spreadRadius: 1,
                blurRadius: 3,
                offset: const Offset(0, 1),
              ),
            ],
            border: Border.all(color: color.withOpacity(0.2), width: 1),
          ),
          child: Padding(
            padding: const EdgeInsets.all(12),
            child: Row(
              children: [
                Container(
                  padding: const EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: color.withOpacity(0.1),
                    shape: BoxShape.circle,
                  ),
                  child: Icon(icon, color: color, size: 20),
                ),
                const SizedBox(width: 12),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      value,
                      style: TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                        color: color,
                      ),
                    ),
                    const SizedBox(height: 2),
                    Text(
                      label,
                      style: TextStyle(
                        fontSize: 12,
                        color: themeExt.textSecondary,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
  
  // 告警状态统计卡片
  Widget _buildAlertStatusCard({
    required BuildContext context,
    required IconData icon,
    required String label,
    required String value,
    required Color color,
    Function()? onTap,
  }) {
    final themeExt = AppTheme.extensionOf(context);
    
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(themeExt.cardRadius),
        child: Container(
          decoration: BoxDecoration(
            color: themeExt.cardBackground,
            borderRadius: BorderRadius.circular(themeExt.cardRadius),
            boxShadow: [
              BoxShadow(
                color: themeExt.cardShadow.withOpacity(0.1),
                spreadRadius: 1,
                blurRadius: 3,
                offset: const Offset(0, 1),
              ),
            ],
            border: Border.all(color: color.withOpacity(0.2), width: 1),
          ),
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 8),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                  padding: const EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: color.withOpacity(0.1),
                    shape: BoxShape.circle,
                  ),
                  child: Icon(icon, color: color, size: 18),
                ),
                const SizedBox(height: 6),
                Text(
                  value, 
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    color: color,
                  ),
                ),
                const SizedBox(height: 3),
                Text(
                  label,
                  style: TextStyle(
                    fontSize: 10,
                    color: themeExt.textSecondary,
                    fontWeight: FontWeight.w500,
                    height: 1.2,
                  ),
                  textAlign: TextAlign.center,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
  
  // 创建告警卡片
  Widget _buildAlertCard({
    required AlertLog alert,
    required BuildContext context,
  }) {
    final themeExt = AppTheme.extensionOf(context);
    
    // 防止空值导致的错误
    try {
      final Color levelColor = controller.getAlertLevelColor(alert.level);
      final Color bgColor = levelColor.withOpacity(0.1);
      
      return Container(
        margin: const EdgeInsets.only(bottom: 12),
        decoration: BoxDecoration(
          color: themeExt.cardBackground,
          borderRadius: BorderRadius.circular(themeExt.cardRadius),
          border: Border.all(color: bgColor, width: 1),
          boxShadow: [
            BoxShadow(
              color: themeExt.cardShadow.withOpacity(0.05),
              blurRadius: 3,
              offset: const Offset(0, 1),
            ),
          ],
        ),
        child: Material(
          color: Colors.transparent,
          borderRadius: BorderRadius.circular(themeExt.cardRadius),
          child: InkWell(
            borderRadius: BorderRadius.circular(themeExt.cardRadius),
            onTap: () => controller.viewAlertDetail(alert.logId ?? 0),
            child: Padding(
              padding: const EdgeInsets.all(14),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Expanded(
                        child: Row(
                          children: [
                            Container(
                              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                              decoration: BoxDecoration(
                                color: bgColor,
                                borderRadius: BorderRadius.circular(themeExt.tagRadius),
                              ),
                              child: Text(
                                alert.getLevelDesc(),
                                style: TextStyle(
                                  fontSize: 12,
                                  color: levelColor,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                            const SizedBox(width: 8),
                            Expanded(
                              child: Text(
                                alert.alertName ?? LocaleKeys.unknownAlert.tr,
                                style: const TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: 14,
                                ),
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                          ],
                        ),
                      ),
                      if (alert.status == 0) // 如果是未确认的告警
                        TextButton(
                          onPressed: () => controller.confirmAlert(alert.logId ?? 0),
                          style: TextButton.styleFrom(
                            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
                            minimumSize: const Size(60, 24),
                            foregroundColor: Theme.of(context).primaryColor,
                            backgroundColor: Theme.of(context).primaryColor.withOpacity(0.1),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(themeExt.tagRadius),
                            ),
                          ),
                          child: Text(LocaleKeys.confirm.tr, style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w600)),
                        ),
                    ],
                  ),
                  const SizedBox(height: 12),
                  _buildInfoRow(
                    icon: Icons.device_hub,
                    text: '${LocaleKeys.device.tr}: ${alert.deviceName ?? alert.deviceSn ?? LocaleKeys.unknownDevice.tr}',
                    themeExt: themeExt,
                  ),
                  const SizedBox(height: 6),
                  _buildInfoRow(
                    icon: Icons.warning_amber,
                    text: '${LocaleKeys.content.tr}: ${alert.content ?? LocaleKeys.noDetailInfo.tr}',
                    themeExt: themeExt,
                    isExpanded: true,
                  ),
                  const SizedBox(height: 6),
                  _buildInfoRow(
                    icon: Icons.access_time,
                    text: '${LocaleKeys.time.tr}: ${alert.alertTime ?? LocaleKeys.unknownTime.tr}',
                    themeExt: themeExt,
                  ),
                ],
              ),
            ),
          ),
        ),
      );
    } catch (e) {
      // 发生任何错误时返回简单的占位卡片
      debugPrint('渲染告警卡片错误: $e');
      return Card(
        margin: const EdgeInsets.only(bottom: 12),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(themeExt.cardRadius),
        ),
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Text(
            LocaleKeys.alertLoadError.tr,
            style: TextStyle(color: themeExt.textSecondary),
          ),
        ),
      );
    }
  }
  
  // 提取出的信息行组件
  Widget _buildInfoRow({
    required IconData icon,
    required String text,
    required AppThemeExtension themeExt,
    bool isExpanded = false,
  }) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Icon(icon, size: 16, color: themeExt.textSecondary),
        const SizedBox(width: 8),
        isExpanded
            ? Expanded(
                child: Text(
                  text,
                  style: TextStyle(
                    fontSize: 13,
                    color: themeExt.textSecondary,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              )
            : Text(
                text,
                style: TextStyle(
                  fontSize: 13,
                  color: themeExt.textSecondary,
                ),
              ),
      ],
    );
  }

  // 用户头像组件
  Widget _buildUserAvatar(BuildContext context) {
    final String avatarUrl = controller.userService.avatar;
    
    if (avatarUrl.isNotEmpty) {
      return Container(
        width: 32,
        height: 32,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          border: Border.all(
            color: Theme.of(context).primaryColor.withOpacity(0.2),
            width: 1.5,
          ),
        ),
        child: ClipOval(
          child: Image.network(
            avatarUrl,
            width: 30,
            height: 30,
            fit: BoxFit.cover,
            errorBuilder: (context, error, stackTrace) {
              // 加载失败时显示默认头像图标
              return _buildDefaultAvatar(context);
            },
            loadingBuilder: (context, child, loadingProgress) {
              if (loadingProgress == null) return child;
              return Center(
                child: SizedBox(
                  width: 16,
                  height: 16,
                  child: CircularProgressIndicator(
                    strokeWidth: 2,
                    color: Theme.of(context).primaryColor,
                    value: loadingProgress.expectedTotalBytes != null
                        ? loadingProgress.cumulativeBytesLoaded / 
                          loadingProgress.expectedTotalBytes!
                        : null,
                  ),
                ),
              );
            },
          ),
        ),
      );
    } else {
      // 没有头像URL时显示默认图标
      return _buildDefaultAvatar(context);
    }
  }
  
  Widget _buildDefaultAvatar(BuildContext context) {
    return Container(
      width: 32,
      height: 32,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        color: Theme.of(context).primaryColor.withOpacity(0.1),
      ),
      child: Center(
        child: Icon(
          Icons.person,
          color: Theme.of(context).primaryColor,
          size: 20,
        ),
      ),
    );
  }
} 